﻿using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;

namespace RuoVea.ExUtil.Validate;

/// <summary>
/// 描 述：密码
/// </summary>
public sealed class PassworldAttribute : ValidationAttribute
{
    bool _superPass = false;
    int _minLength = 8;
    int _maxLength = 64;

    /// <summary>
    /// 密码验证规则
    /// </summary>
    /// <param name="superPass">超级密码</param>
    /// <param name="minLength">密码最小长度</param>  
    /// <param name="maxLength">密码最大长度</param>  
    /// <param name="msg">提示消息</param>
    public PassworldAttribute(bool superPass = false, int minLength = 8, int maxLength = 64, string msg = null)
    {
        _superPass = superPass;
        _minLength = minLength;
        _maxLength = maxLength;

        if (msg.NotNullOrWhiteSpace())
            this.ErrorMessage = msg;
        else
        {
            if (superPass)
                this.ErrorMessage = "{0}:必须有（数字、小写字母、大写字母、特殊符号，至少" + _minLength + "个字符，最多" + _maxLength + "个字符）组成";
            else
                this.ErrorMessage = "{0}:必须有（数字、小写字母、大写字母，至少" + _maxLength + "个字符，最多" + _maxLength + "个字符）组成";
        }
    }

    /// <summary>
    /// 证请求结果
    /// </summary>
    /// <param name="value">校验内容</param>
    /// <param name="validationContext">报错指定对象</param>
    /// <returns>证请求结果的容器</returns>
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            //                Regex r = new Regex(@"
            //(?=.*[0-9])                     #必须包含数字
            //(?=.*[a-z])                  #必须包含小写或大写字母
            //(?=.*[A-Z])                  #必须包含小写或大写字母
            //(?=([\x21-\x7e]+)[^a-zA-Z0-9])  #必须包含特殊符号
            //.{8,30}                         #至少8个字符，最多30个字符
            //");

            Regex r = new Regex(@"^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{" + _minLength + "," + _maxLength + "}$");

            if (_superPass)
                r = new Regex(@"^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=([\x21-\x7e]+)[^a-zA-Z0-9]).{" + _minLength + "," + _maxLength + "}$");
            else
                r = new Regex(@"^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{" + _minLength + "," + _maxLength + "}$");

            if (!r.IsMatch(value?.ToString()))
            {
                var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                return new ValidationResult(errorMessage);
            }
        }
        return ValidationResult.Success;
    }
}
